package com.teacher.game.state;

import android.graphics.Color;
import android.view.MotionEvent;
import com.teacher.ellio.Assets;
import com.teacher.ellio.GameMainActivity;
import com.teacher.game.framework.util.Painter;
import com.teacher.game.framework.util.ScoreManager;
import com.teacher.game.framework.util.UIButton;
import com.teacher.game.framework.util.ParticleSystem;
import com.teacher.game.framework.util.ParticleEffects;

/**
 * 游戏结束状态 - 增强版，支持庆祝动画和丰富的统计展示
 * 
 * Story 5.1: 游戏结束界面增强
 * - 新纪录庆祝动画和粒子特效
 * - 详细的游戏表现分析和等级系统
 * - 成就展示和社交分享元素
 * - 流畅的视觉过渡和用户体验
 * 
 * @version 3.0 - Story 5.1 游戏结束界面增强
 * @since 2025-09-12
 */
public class GameOverState extends State {
    
    private ScoreManager scoreManager;
    private UIButton restartButton;
    private UIButton menuButton;
    private UIButton shareButton; // 新增分享按钮
    
    // 粒子特效系统
    private ParticleSystem particleSystem;
    private boolean celebrationStarted = false;
    
    // 显示内容
    private String currentScoreText;
    private String highScoreText;
    private String gameStatsText;
    private String gameTimeText;
    private String detailedStatsText;
    private String achievementText;
    private String levelUpText;
    private boolean isNewRecord;
    private boolean hasLevelUp;
    
    // 动画效果
    private float titlePulse = 0;
    private float newRecordAlpha = 1.0f;
    private boolean newRecordFade = false;
    private float celebrationTimer = 0;
    private float backgroundWave = 0;
    private float starRotation = 0;
    private float scoreCountUpValue = 0;
    private float scoreCountUpTarget = 0;
    private boolean scoreAnimationComplete = false;
    
    // 界面状态
    private float stateTimer = 0;
    private boolean fullyLoaded = false;
    private final float LOAD_DELAY = 0.5f; // 延迟显示，增加仪式感
    
    /**
     * 构造函数
     * @param scoreManager 得分管理器
     */
    public GameOverState(ScoreManager scoreManager) {
        this.scoreManager = scoreManager;
        this.isNewRecord = scoreManager.isNewRecord();
        this.scoreCountUpTarget = scoreManager.getCurrentScore();
        this.hasLevelUp = checkForLevelUp();
    }
    
    @Override
    public void init() {
        // 初始化粒子系统用于庆祝特效
        particleSystem = new ParticleSystem(200, 50);
        particleSystem.setEnabled(true);
        
        // 创建按钮 - 重新布局支持三个按钮
        restartButton = new UIButton(200, 350, 300, 390, Assets.start, Assets.startDown);
        menuButton = new UIButton(320, 350, 420, 390, Assets.score, Assets.scoreDown);
        shareButton = new UIButton(440, 350, 540, 390, Assets.score, Assets.scoreDown); // 复用素材
        
        // 准备显示文本
        prepareDisplayTexts();
        
        // 准备庆祝效果
        if (isNewRecord && !celebrationStarted) {
            startCelebration();
        }
        
        // 停止背景音乐
        Assets.stopBgMusic();
        
        // 播放游戏结束音效
        Assets.playSound(Assets.hitSoundId);
        
        // 如果是新纪录，延迟播放庆祝音效
        if (isNewRecord) {
            new android.os.Handler().postDelayed(() -> {
                Assets.playSound(Assets.startId); // 胜利音效
            }, 800);
        }
    }
    
    /**
     * 检查是否有等级提升
     */
    private boolean checkForLevelUp() {
        // 简化实现：基于分数检查等级提升
        int oldLevel = (scoreManager.getHighScore() - scoreManager.getCurrentScore()) / 1000;
        int newLevel = scoreManager.getHighScore() / 1000;
        return newLevel > oldLevel;
    }
    
    /**
     * 开始庆祝动画
     */
    private void startCelebration() {
        celebrationStarted = true;
        
        // 创建新纪录庆祝特效
        ParticleEffects.createNewRecordCelebration(particleSystem, 
                                                 GameMainActivity.GAME_WIDTH / 2, 
                                                 GameMainActivity.GAME_HEIGHT / 2);
        
        // 如果还有等级提升，添加额外特效
        if (hasLevelUp) {
            ParticleEffects.createLevelUpEffect(particleSystem,
                                              GameMainActivity.GAME_WIDTH / 2,
                                              200);
        }
    }
    
    /**
     * 准备所有要显示的文本内容
     */
    private void prepareDisplayTexts() {
        currentScoreText = "本次得分: " + scoreManager.getCurrentScore();
        highScoreText = "历史最高: " + scoreManager.getHighScore();
        gameTimeText = "游戏时长: " + scoreManager.getFormattedGameTime();
        gameStatsText = scoreManager.getGameStats();
        detailedStatsText = scoreManager.getCurrentGameStats();
        
        // 成就文本
        achievementText = generateAchievementText();
        
        // 等级提升文本
        if (hasLevelUp) {
            levelUpText = "恭喜升级到 Lv." + scoreManager.getPlayerLevel() + "!";
        }
    }
    
    /**
     * 生成成就文本
     */
    private String generateAchievementText() {
        StringBuilder achievements = new StringBuilder();
        
        // 基于当前游戏表现生成成就
        if (scoreManager.getCurrentScore() >= 1000) {
            achievements.append("🏆 得分达人 ");
        }
        if (scoreManager.getBlocksPassedCount() >= 20) {
            achievements.append("🚧 障碍大师 ");
        }
        if (scoreManager.getGameTime() >= 60) {
            achievements.append("⏰ 持久战士 ");
        }
        if (scoreManager.getPowerUpsCollected() >= 5) {
            achievements.append("💎 收集家 ");
        }
        
        return achievements.length() > 0 ? achievements.toString() : "继续努力解锁成就！";
    }
    
    @Override
    public void update(float delta) {
        stateTimer += delta;
        
        // 延迟显示逻辑
        if (stateTimer >= LOAD_DELAY) {
            fullyLoaded = true;
        }
        
        // 更新粒子系统
        particleSystem.update(delta);
        
        // 分数计数动画
        updateScoreCountUp(delta);
        
        // 更新各种视觉效果
        updateVisualEffects(delta);
        
        // 庆祝计时器
        if (celebrationStarted) {
            celebrationTimer += delta;
        }
    }
    
    /**
     * 更新分数计数动画
     */
    private void updateScoreCountUp(float delta) {
        if (!scoreAnimationComplete && fullyLoaded) {
            scoreCountUpValue += (scoreCountUpTarget * delta * 2); // 2秒内计数完成
            if (scoreCountUpValue >= scoreCountUpTarget) {
                scoreCountUpValue = scoreCountUpTarget;
                scoreAnimationComplete = true;
            }
        }
    }
    
    /**
     * 更新视觉效果
     */
    private void updateVisualEffects(float delta) {
        // 标题脉动动画
        titlePulse += delta * 3;
        
        // 背景波浪效果
        backgroundWave += delta * 0.8f;
        
        // 星星旋转效果
        starRotation += delta * 90; // 每秒90度
        
        // 新纪录闪烁动画
        if (isNewRecord) {
            if (newRecordFade) {
                newRecordAlpha -= delta * 2;
                if (newRecordAlpha <= 0.3f) {
                    newRecordAlpha = 0.3f;
                    newRecordFade = false;
                }
            } else {
                newRecordAlpha += delta * 2;
                if (newRecordAlpha >= 1.0f) {
                    newRecordAlpha = 1.0f;
                    newRecordFade = true;
                }
            }
        }
    }
    
    @Override
    public void render(Painter g) {
        // 渲染增强背景
        renderEnhancedBackground(g);
        
        // 如果还在加载延迟期，只显示简单加载提示
        if (!fullyLoaded) {
            renderLoadingState(g);
            return;
        }
        
        // 渲染粒子特效（背景层）
        particleSystem.render(g);
        
        // 渲染标题区域
        renderTitleSection(g);
        
        // 渲染分数区域（带动画）
        renderAnimatedScoreSection(g);
        
        // 渲染详细统计
        renderEnhancedStatsSection(g);
        
        // 渲染成就区域
        renderAchievementSection(g);
        
        // 渲染按钮区域
        renderEnhancedButtons(g);
        
        // 渲染装饰元素
        renderDecorations(g);
    }
    
    /**
     * 渲染增强背景
     */
    private void renderEnhancedBackground(Painter g) {
        // 基础半透明背景
        g.setColor(Color.argb(220, 0, 0, 0));
        g.fillRect(0, 0, GameMainActivity.GAME_WIDTH, GameMainActivity.GAME_HEIGHT);
        
        // 动态渐变效果
        if (isNewRecord) {
            float waveAlpha = (float) Math.sin(backgroundWave) * 0.2f + 0.3f;
            g.setColor(Color.argb((int)(50 * waveAlpha), 255, 215, 0)); // 金色渐变
            g.fillRect(0, 0, GameMainActivity.GAME_WIDTH, GameMainActivity.GAME_HEIGHT);
        }
        
        // 中央面板背景
        g.setColor(Color.argb(150, 30, 30, 30));
        g.fillRect(100, 80, 600, 280);
        
        // 面板边框
        g.setColor(isNewRecord ? Color.rgb(255, 215, 0) : Color.WHITE);
        g.fillRect(100, 80, 600, 3); // 顶边
        g.fillRect(100, 357, 600, 3); // 底边
        g.fillRect(100, 80, 3, 280); // 左边
        g.fillRect(697, 80, 3, 280); // 右边
    }
    
    /**
     * 渲染加载状态
     */
    private void renderLoadingState(Painter g) {
        g.setColor(Color.argb(220, 0, 0, 0));
        g.fillRect(0, 0, GameMainActivity.GAME_WIDTH, GameMainActivity.GAME_HEIGHT);
        
        g.setColor(Color.WHITE);
        g.drawString("正在统计游戏结果...", 320, 225);
        
        // 简单的加载动画
        int dots = ((int)(stateTimer * 4) % 4);
        String loadingText = "加载中";
        for (int i = 0; i < dots; i++) {
            loadingText += ".";
        }
        g.drawString(loadingText, 360, 250);
    }
    
    /**
     * 渲染标题区域
     */
    private void renderTitleSection(Painter g) {
        // 游戏结束标题（带脉动效果）
        float titleScale = 1.0f + (float) Math.sin(titlePulse) * 0.08f;
        
        // 标题阴影
        g.setColor(Color.argb(100, 0, 0, 0));
        g.drawString("游戏结束", 352, 102);
        
        // 主标题
        g.setColor(Color.WHITE);
        g.drawString("游戏结束", 350, 100);
        
        // 新纪录提示（带闪烁效果和装饰）
        if (isNewRecord) {
            int alpha = (int) (255 * newRecordAlpha);
            g.setColor(Color.argb(alpha, 255, 215, 0)); // 金色
            g.drawString("🏆 恭喜！创造新纪录！ 🏆", 260, 130);
            
            // 新纪录装饰星星
            renderCelebrationStars(g, alpha);
        }
        
        // 等级提升提示
        if (hasLevelUp && levelUpText != null) {
            g.setColor(Color.rgb(144, 238, 144)); // 浅绿色
            g.drawString(levelUpText, 300, 155);
        }
    }
    
    /**
     * 渲染庆祝星星装饰
     */
    private void renderCelebrationStars(Painter g, int alpha) {
        g.setColor(Color.argb(alpha, 255, 215, 0));
        
        // 在标题周围绘制旋转的星星
        int centerX = 400;
        int centerY = 130;
        int radius = 80;
        
        for (int i = 0; i < 6; i++) {
            double angle = (starRotation + i * 60) * Math.PI / 180;
            int starX = centerX + (int)(radius * Math.cos(angle));
            int starY = centerY + (int)(radius * Math.sin(angle));
            g.drawString("⭐", starX, starY);
        }
    }
    
    /**
     * 渲染动画分数区域
     */
    private void renderAnimatedScoreSection(Painter g) {
        int startY = 180;
        
        // 当前得分（带计数动画）
        g.setColor(Color.WHITE);
        if (scoreAnimationComplete) {
            g.drawString(currentScoreText, 300, startY);
        } else {
            g.drawString("本次得分: " + (int)scoreCountUpValue, 300, startY);
        }
        
        // 最高分用不同颜色突出显示
        if (isNewRecord) {
            g.setColor(Color.YELLOW);
        } else {
            g.setColor(Color.rgb(192, 192, 192)); // LIGHT_GRAY
        }
        g.drawString(highScoreText, 300, startY + 25);
        
        // 游戏时长
        g.setColor(Color.CYAN);
        g.drawString(gameTimeText, 300, startY + 50);
    }
    
    /**
     * 渲染增强统计区域
     */
    private void renderEnhancedStatsSection(Painter g) {
        int startY = 255;
        
        // 本局详细统计
        g.setColor(Color.rgb(255, 215, 0)); // 金色标题
        g.drawString("本局表现分析:", 120, startY);
        
        g.setColor(Color.WHITE);
        g.drawString(detailedStatsText, 140, startY + 20);
        
        // 额外分析数据
        renderPerformanceAnalysis(g, startY + 40);
        
        // 历史统计对比
        g.setColor(Color.rgb(192, 192, 192));
        g.drawString("历史统计:", 120, startY + 80);
        g.drawString(gameStatsText, 140, startY + 100);
    }
    
    /**
     * 渲染表现分析
     */
    private void renderPerformanceAnalysis(Painter g, int y) {
        g.setColor(Color.CYAN);
        
        // 计算表现评级
        String performance = calculatePerformanceRating();
        g.drawString("表现评级: " + performance, 140, y);
        
        // 效率分析
        if (scoreManager.getGameTime() > 0) {
            int scorePerSecond = (int)(scoreManager.getCurrentScore() / scoreManager.getGameTime());
            g.drawString("得分效率: " + scorePerSecond + "分/秒", 140, y + 20);
        }
    }
    
    /**
     * 计算表现评级
     */
    private String calculatePerformanceRating() {
        int score = scoreManager.getCurrentScore();
        if (score >= 2000) return "S+ (传奇)";
        if (score >= 1500) return "S (大师)";
        if (score >= 1000) return "A (优秀)";
        if (score >= 500) return "B (良好)";
        return "C (继续努力)";
    }
    
    /**
     * 渲染成就区域
     */
    private void renderAchievementSection(Painter g) {
        if (achievementText != null && !achievementText.contains("继续努力")) {
            g.setColor(Color.rgb(255, 165, 0)); // 橙色
            g.drawString("本局成就: " + achievementText, 120, 380);
        }
    }
    
    /**
     * 渲染增强按钮区域
     */
    private void renderEnhancedButtons(Painter g) {
        // 渲染按钮发光效果
        if (isNewRecord) {
            renderButtonGlowEffect(g);
        }
        
        // 渲染按钮
        restartButton.render(g);
        menuButton.render(g);
        shareButton.render(g);
        
        // 按钮标签
        g.setColor(Color.WHITE);
        g.drawString("再来一局", 215, 410);
        g.drawString("主菜单", 340, 410);
        g.drawString("分享成绩", 455, 410);
    }
    
    /**
     * 渲染按钮发光效果
     */
    private void renderButtonGlowEffect(Painter g) {
        float glowIntensity = (float) Math.sin(titlePulse) * 0.3f + 0.7f;
        int glowAlpha = (int) (30 * glowIntensity);
        
        g.setColor(Color.argb(glowAlpha, 255, 215, 0));
        // 为重新开始按钮添加发光
        g.fillRect((int)restartButton.getX() - 5, (int)restartButton.getY() - 5, 
                  restartButton.getWidth() + 10, restartButton.getHeight() + 10);
    }
    
    /**
     * 渲染装饰元素
     */
    private void renderDecorations(Painter g) {
        // 在角落添加装饰性跑步小人
        Assets.runAnim.render(g, 50, 50);
        Assets.runAnim.render(g, 700, 380);
        
        // 如果庆祝状态，添加额外装饰
        if (isNewRecord && celebrationTimer > 2.0f) {
            renderVictoryDecorations(g);
        }
    }
    
    /**
     * 渲染胜利装饰
     */
    private void renderVictoryDecorations(Painter g) {
        // 简单的胜利装饰：闪烁的边框
        float flashAlpha = (float) Math.sin(celebrationTimer * 6) * 0.5f + 0.5f;
        int alpha = (int)(100 * flashAlpha);
        
        g.setColor(Color.argb(alpha, 255, 215, 0));
        // 装饰性边框闪烁
        g.fillRect(0, 0, GameMainActivity.GAME_WIDTH, 5);
        g.fillRect(0, GameMainActivity.GAME_HEIGHT - 5, GameMainActivity.GAME_WIDTH, 5);
        g.fillRect(0, 0, 5, GameMainActivity.GAME_HEIGHT);
        g.fillRect(GameMainActivity.GAME_WIDTH - 5, 0, 5, GameMainActivity.GAME_HEIGHT);
    }
    
    @Override
    public boolean onTouch(MotionEvent e, int scaleX, int scaleY) {
        if (e.getAction() == MotionEvent.ACTION_DOWN) {
            // 处理按钮按下
            restartButton.onTouchDown(scaleX, scaleY);
            menuButton.onTouchDown(scaleX, scaleY);
            shareButton.onTouchDown(scaleX, scaleY);
            
        } else if (e.getAction() == MotionEvent.ACTION_UP) {
            // 处理按钮释放
            if (restartButton.isPressed(scaleX, scaleY)) {
                restartButton.cancel();
                onRestartGame();
                return true;
                
            } else if (menuButton.isPressed(scaleX, scaleY)) {
                menuButton.cancel();
                onReturnToMenu();
                return true;
                
            } else if (shareButton.isPressed(scaleX, scaleY)) {
                shareButton.cancel();
                onShareScore();
                return true;
                
            } else {
                // 取消所有按钮状态
                restartButton.cancel();
                menuButton.cancel();
                shareButton.cancel();
            }
        }
        return true;
    }
    
    /**
     * 重新开始游戏
     */
    private void onRestartGame() {
        // 播放按钮音效
        Assets.playSound(Assets.startId);
        
        // 保留当前难度设置，直接进入游戏
        PlayState newGame = new PlayState();
        if (scoreManager instanceof ScoreManager) {
            // 传递难度设置
            newGame.setDifficulty(DifficultySelectState.DIFFICULTY_NORMAL); // 默认难度
        }
        setCurrState(newGame);
    }
    
    /**
     * 返回主菜单
     */
    private void onReturnToMenu() {
        // 播放按钮音效
        Assets.playSound(Assets.startId);
        
        // 跳转到菜单状态
        setCurrState(new MenuState());
    }
    
    /**
     * 分享分数功能
     */
    private void onShareScore() {
        // 播放按钮音效
        Assets.playSound(Assets.startId);
        
        // 生成分享文本
        String shareText = generateShareText();
        
        // 简单实现：显示分享文本（实际项目中可集成社交分享）
        android.util.Log.d("GameOverState", "分享内容: " + shareText);
        
        // 临时反馈：跳转到得分界面显示详细统计
        setCurrState(new ScoreState());
    }
    
    /**
     * 生成分享文本
     */
    private String generateShareText() {
        StringBuilder share = new StringBuilder();
        share.append("我在EllioAndroid跑酷游戏中获得了").append(scoreManager.getCurrentScore()).append("分！");
        
        if (isNewRecord) {
            share.append("🏆创造了新纪录！");
        }
        
        share.append(" 游戏时长: ").append(scoreManager.getFormattedGameTime());
        share.append(" 表现评级: ").append(calculatePerformanceRating());
        
        return share.toString();
    }
    
    /**
     * 获取得分管理器
     * @return 得分管理器实例
     */
    public ScoreManager getScoreManager() {
        return scoreManager;
    }
    
    /**
     * 检查是否是新纪录
     * @return 是否创造了新纪录
     */
    public boolean isNewRecord() {
        return isNewRecord;
    }
    
    /**
     * 检查是否有等级提升
     * @return 是否有等级提升
     */
    public boolean hasLevelUp() {
        return hasLevelUp;
    }
}